#!/usr/bin/env node

const fs = require('fs');
const path = require('path');
const {execFileSync} = require('child_process');

const cliPath = path.join(__dirname, '..', 'cli');
const npmPath = path.join(cliPath, 'npm');
const cargoTomlPath = path.join(cliPath, 'Cargo.toml');

const npmMetadata = require(path.join(npmPath, 'package.json'));
const npmVersion = npmMetadata.version;

const cargoMetadata = fs.readFileSync(cargoTomlPath, 'utf8')
const cargoVersionMatch = cargoMetadata.match(/version = "([^"\n]+)"/);
const cargoVersion = cargoVersionMatch[1];

if (npmVersion !== cargoVersion) {
  console.error(`NPM version ${npmVersion} does not match Cargo version ${cargoVersion}`);
  process.exit(1);
}

const arg = process.argv[2];

if (!arg) {
  console.log([
    `Usage: script/version major | minor | patch | <version-number>`,
    '',
    'Update the CLI version by the given increment or to the given',
    'version number, creating a commit and tag for the new version.',
    ''
  ].join('\n'))
  process.exit(1);
}

if (arg) {
  // Check that working directory is clean
  const diff = execFileSync(
    'git',
    ['diff', '--stat'],
    {encoding: 'utf8'}
  );
  if (diff.length !== 0) {
    console.error('There are uncommited changes.');
    process.exit(1);
  }

  const newVersion = execFileSync(
    'npm',
    ['version', process.argv[2], '--git-tag-version=false'],
    {cwd: npmPath, encoding: 'utf8'}
  ).trim().replace(/^v/, '');
  const newCargoVersionLine = cargoVersionMatch[0].replace(cargoVersion, newVersion);
  const newCargoMetadata = cargoMetadata.replace(cargoVersionMatch[0], newCargoVersionLine);
  fs.writeFileSync(cargoTomlPath, newCargoMetadata, 'utf8');
  execFileSync('cargo', ['build'], {cwd: cliPath});
  execFileSync('git', ['commit', '-a', '-m', newVersion]);
  execFileSync('git', ['tag', newVersion]);
  console.log(newVersion)
} else {
  console.log(npmVersion);
}
